package controllers;

import models.*;
import play.db.jpa.JPA;
import play.mvc.Controller;
import utils.Strings;

import javax.persistence.EntityManager;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by xuyang on 2018/1/11.
 */
public class Aircraft extends Controller {

    public static void index(String aircraft, String actype, String airlines) {

        EntityManager em = JPA.em();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<TB005> query = cb.createQuery(TB005.class);
        Root<TB005> ac = query.from(TB005.class);

        final List<Predicate> predicates = new ArrayList<Predicate>();

        if (aircraft != null && !aircraft.isEmpty()) {
//            query = TB005.find("aircraft_id like ? order by aircraft_id", "%"+aircraft+"%");
            aircraft = aircraft.toUpperCase();
            predicates.add(cb.like(ac.<String>get("aircraft_id"), "%"+aircraft+"%"));
        }

        if (actype != null && !actype.isEmpty()) {
            Join<TB005, TB006> at = ac.join("aircraft_type", JoinType.LEFT);
            actype = actype.toUpperCase();
            predicates.add(cb.like(at.<String>get("aircraft_type"), "%"+actype+"%"));
        }

        if (airlines != null && !airlines.isEmpty()) {
            Join<TB005, TB007> al = ac.join("airlines", JoinType.LEFT);
            airlines = airlines.toUpperCase();
            predicates.add(cb.equal(al.<String>get("code2"), airlines));
        }

        query.select(ac);
        query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])))
                .orderBy(cb.asc(ac.<String>get("aircraft_id")));

        List<TB005> items = em.createQuery(query)
                .setMaxResults(50)
                .getResultList();

        render(items, aircraft, actype, airlines);
    }


    public static void edit(String id) {
        String title = "Edit Aircraft";
        List<TB006> allAircraftTypes = TB006.findAll();
        List<TB007> allAirlines = TB007.findAll();


        allAircraftTypes.sort(new Comparator<TB006>() {
            @Override
            public int compare(TB006 o1, TB006 o2) {
                return o1.aircraft_type.compareTo(o2.aircraft_type);
            }
        });
        allAirlines.sort(new Comparator<TB007>() {
            @Override
            public int compare(TB007 o1, TB007 o2) {
                return o1.code2.compareTo(o2.code2);
            }
        });

        if (id == null) {
            // new
            title = "Create New Aircraft";
            render(allAircraftTypes, allAirlines);
        }

        TB005 entity = TB005.findById(id);
        if (entity == null) {
            error(500, "Aircraft " + id + " doesn't exist." );
        }

        render(allAircraftTypes, allAirlines, title, entity);
    }

    public static void save(String id, String aircraft_id, String aircraft_type, String airlines) {
        if (params.get("delete") != null) {
            delete(id);
            index(null, null, null);
        }

        try {
            TB005 entity = null;
            TB006 tb006 = (TB006) TB006.find("aircraft_type=?", aircraft_type).fetch().get(0);
            TB007 tb007 = (TB007) TB007.find("code2=?", airlines).fetch().get(0);

            List<String> savedIds = new ArrayList<>();

            if (Strings.isNullOrEmpty(id)) {
                String[] aircraftIds = aircraft_id.split("[\\s,，;；]+");
                for (String acid : aircraftIds) {
                    if (acid.trim().equalsIgnoreCase("")) {
                        continue;
                    }
                    entity = new TB005(acid);
                    entity.airlines = tb007;
                    entity.aircraft_type = tb006;

                    entity.save();

                    savedIds.add(acid);
                }
            } else {
                entity = TB005.findById(id);
                entity.airlines = tb007;
                entity.aircraft_type = tb006;

                entity.save();

                savedIds.add(entity.aircraft_id);
            }

            String idString = String.join(",", savedIds);
            flash.success("Save aircraft " + idString + " successfully!");
            edit(savedIds.get(0));
        } catch (Exception e) {
            flash.error("Save aircraft failed: " + e.getLocalizedMessage());
            e.printStackTrace();
            error(500, "Save aircraft failed: " + e.getLocalizedMessage());
        }
    }

    public static void delete(String id) {
        TB005 entity = TB005.findById(id);
        entity.delete();

        flash.success("Successfully deleted aircraft " + id);

        index(null, null, null);
    }

}
